package com.bootdo.mq;
import com.bootdo.common.redisUtils.ObjectUtils;
import com.bootdo.common.utils.Hog;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.ChannelAwareMessageListener;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;



//@Configuration
public class PrintMessageQueue {

    public static final String YISONGKEY = "com.hebeiyisong.topic";

    @Autowired
    private RabbitAdmin rabbitAdmin;

    @Autowired
    private ConnectionFactory connectionFactory;



    /**
     * 打印队列
     * @return
     */
    @Bean
    Queue printQueue() {
        Queue queue = new Queue("com.hebeiyisong.printqueue", true);
        this.rabbitAdmin.declareQueue(queue);
        return queue;
    }





    /**
     * 交换器
     * @return
     */
    @Bean
    TopicExchange hebeiyisongPrintExchange() {
        TopicExchange contractTopicExchange = new TopicExchange("com.hebeiyisong.topic",true,true);
        this.rabbitAdmin.declareExchange(contractTopicExchange);
        return contractTopicExchange;
    }




    /**
     * 绑定队列
     * @return
     */
    @Bean
    public Binding printBinding() {
        return BindingBuilder.bind(printQueue()).to(hebeiyisongPrintExchange()).with("print.yisong.*");
    }



    @Bean
    public SimpleMessageListenerContainer lockSystemMessageContainer() {
        SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(connectionFactory);
        container.setQueues(printQueue());
        container.setExposeListenerChannel(true);
        container.setMaxConcurrentConsumers(1);
        container.setConcurrentConsumers(1);
        container.setAcknowledgeMode(AcknowledgeMode.MANUAL); //设置确认模式手工确认
        container.setMessageListener(new ChannelAwareMessageListener() {
            @Override
            public void onMessage(Message message, Channel channel) throws Exception {
                byte[] body = message.getBody();
                Hog.e("打印机队列等待消息..."+body.length);
                try{
                    Object object =  ObjectUtils.unserialize(body);
                    //objectDistribution(object);
                }catch (Exception e){
                    e.printStackTrace();
                }finally {
                    //确认消息
                    channel.basicAck(message.getMessageProperties().getDeliveryTag(), false); //确认消息成功消费
                }
            }
        });
        return container;

  }






}
